package com.tree.treeoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.treeoj.common.ErrorCode;
import com.tree.treeoj.constant.CommonConstant;
import com.tree.treeoj.exception.BusinessException;
import com.tree.treeoj.exception.ThrowUtils;
import com.tree.treeoj.mapper.QuestionBankMapper;
import com.tree.treeoj.model.dto.questionbank.QuestionBankQueryRequest;
import com.tree.treeoj.model.entity.PostThumb;
import com.tree.treeoj.model.entity.QuestionBank;
import com.tree.treeoj.model.entity.User;
import com.tree.treeoj.model.vo.QuestionBankVO;
import com.tree.treeoj.model.vo.UserVO;
import com.tree.treeoj.service.QuestionBankService;
import com.tree.treeoj.service.UserService;
import com.tree.treeoj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author 11818
* @description 针对表【question_bank(题库)】的数据库操作Service实现
* @createDate 2024-03-14 11:34:45
*/
@Service
public class QuestionBankServiceImpl extends ServiceImpl<QuestionBankMapper, QuestionBank>
    implements QuestionBankService{

    @Resource
    UserService userService;
    @Override
    public void validQuestionBank(QuestionBank questionBank, boolean add) {
        if (questionBank == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String title = questionBank.getTitle();
        String content = questionBank.getContent();
        String tags = questionBank.getTags();
        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(title, content, tags), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(title) && title.length() > 80) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
        if (StringUtils.isNotBlank(content) && content.length() > 8192) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "内容过长");
        }
    }

    @Override
    public QuestionBankVO getQuestionBankVo(QuestionBank questionBank, HttpServletRequest request) {
        QuestionBankVO questionBankVo = QuestionBankVO.objToVo(questionBank);
        long questionBankId = questionBank.getId();
        // 1. 关联查询用户信息
        Long userId = questionBank.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
//        questionBankVo.setUser(userVO);
        // 2. 已登录，获取用户点赞、收藏状态
        User loginUser = userService.getLoginUserPermitNull(request);
//        if (loginUser != null) {
//            // 获取点赞
//            QueryWrapper<PostThumb> postThumbQueryWrapper = new QueryWrapper<>();
//            postThumbQueryWrapper.in("postId", questionBankId);
//            postThumbQueryWrapper.eq("userId", loginUser.getId());
//            PostThumb postThumb = postThumbMapper.selectOne(postThumbQueryWrapper);
//            postVO.setHasThumb(postThumb != null);
//            // 获取收藏
//            QueryWrapper<PostFavour> postFavourQueryWrapper = new QueryWrapper<>();
//            postFavourQueryWrapper.in("postId", postId);
//            postFavourQueryWrapper.eq("userId", loginUser.getId());
//            PostFavour postFavour = postFavourMapper.selectOne(postFavourQueryWrapper);
//            postVO.setHasFavour(postFavour != null);
//        }
        return questionBankVo;
    }

    @Override
    public Page<QuestionBankVO> getQuestionBankVoPage(Page<QuestionBank> questionBankPage, HttpServletRequest request) {
        List<QuestionBank> questionBankList = questionBankPage.getRecords();
        Page<QuestionBankVO> questionBankVoPage = new Page<>(questionBankPage.getCurrent(), questionBankPage.getSize(), questionBankPage.getTotal());
        if (CollectionUtils.isEmpty(questionBankList)) {
            return questionBankVoPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = questionBankList.stream().map(QuestionBank::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 已登录，获取用户点赞、收藏状态
        Map<Long, Boolean> postIdHasThumbMap = new HashMap<>();
        Map<Long, Boolean> postIdHasFavourMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            Set<Long> questionBankIdSet = questionBankList.stream().map(QuestionBank::getId).collect(Collectors.toSet());
            loginUser = userService.getLoginUser(request);
            // 获取点赞
            QueryWrapper<PostThumb> postThumbQueryWrapper = new QueryWrapper<>();
            postThumbQueryWrapper.in("questionBankId", questionBankIdSet);
            postThumbQueryWrapper.eq("userId", loginUser.getId());
//            List<PostThumb> postPostThumbList = postThumbMapper.selectList(postThumbQueryWrapper);
//            postPostThumbList.forEach(postPostThumb -> postIdHasThumbMap.put(postPostThumb.getPostId(), true));
            // 获取收藏
//            QueryWrapper<questionBankFavour> questionBankFavourQueryWrapper = new QueryWrapper<>();
//            questionBankFavourQueryWrapper.in("questionBankId", questionBankIdSet);
//            questionBankFavourQueryWrapper.eq("userId", loginUser.getId());
//            List<questionBankFavour> questionBankFavourList = questionBankFavourMapper.selectList(questionBankFavourQueryWrapper);
//            questionBankFavourList.forEach(postFavour -> postIdHasFavourMap.put(questionBankFavour.getPostId(), true));
        }
        // 填充信息
        List<QuestionBankVO> questionBankVoList = questionBankList.stream().map(questionBank -> {
            QuestionBankVO questionBankVo = QuestionBankVO.objToVo(questionBank);
            Long userId = questionBank.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
//            questionBankVo.setUser(userService.getUserVO(user));
//            questionBankVo.setHasThumb(postIdHasThumbMap.getOrDefault(questionBank.getId(), false));
//            questionBankVo.setHasFavour(postIdHasFavourMap.getOrDefault(questionBank.getId(), false));
            return questionBankVo;
        }).collect(Collectors.toList());
        questionBankVoPage.setRecords(questionBankVoList);
        return questionBankVoPage;
    }

    @Override
    public QueryWrapper<QuestionBank> getQueryWrapper(QuestionBankQueryRequest questionBankQueryRequest) {
        QueryWrapper<QuestionBank> queryWrapper = new QueryWrapper<>();
        if (questionBankQueryRequest == null) {
            return queryWrapper;
        }
        String searchText = questionBankQueryRequest.getSearchText();
        String sortField = questionBankQueryRequest.getSortField();
        String sortOrder = questionBankQueryRequest.getSortOrder();
        Long id = questionBankQueryRequest.getId();
        String title = questionBankQueryRequest.getTitle();
        String content = questionBankQueryRequest.getContent();
        List<String> tagList = questionBankQueryRequest.getTags();
        Long userId = questionBankQueryRequest.getUserId();
        // 拼接查询条件
        if (StringUtils.isNotBlank(searchText)) {
            queryWrapper.like("title", searchText).or().like("content", searchText);
        }
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        if (CollectionUtils.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }
}




